/*
 * Copyright (c) 2013 Sqpoll.
 * All rights reserved.
 */
package com.yglab.sqpoll.webapp.controller;

import java.net.URLDecoder;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.yglab.sqpoll.model.Survey;
import com.yglab.sqpoll.service.SurveyService;

/**
 * Handles requests for the poll form page.
 * 
 * @author Younggue Bae
 */
@Controller
@RequestMapping("/pollCreateform*")
public class PollFormController {

	private static final Logger logger = LoggerFactory.getLogger(PollFormController.class);

	@Autowired
	private SurveyService surveyService;

	/**
	 * Shows a form to create a new poll.
	 */
  @RequestMapping(method = RequestMethod.GET)
	protected String showForm(@RequestParam(value="surveyId", required=false, defaultValue="-1") int surveyId,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		logger.debug("surveyId == " + surveyId);

		return "pollCreateform";
	}
	
	@RequestMapping(method = RequestMethod.POST)
  public String onSubmit(@RequestParam("command") String command, @RequestParam("json") String strJson, 
  		HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

		Locale locale = request.getLocale();
		
		strJson = URLDecoder.decode(strJson, "UTF-8");
		
		JSONObject json = new JSONObject(strJson);
		json.put("country", locale.getCountry());
		json.put("language", locale.getLanguage());
		
		logger.debug("pollform: onSubmit called!!!!");
		logger.debug("command == " + command);
		logger.debug("json == " + json);
		
		Survey survey = new Survey();
		survey.toObject(json.toString());
		
		logger.debug("object == " + survey);
		
		int surveyId = survey.getSurveyId();
		if (command.equalsIgnoreCase("insert")) {
			surveyId = surveyService.addSurvey(survey);
			survey.setSurveyId(surveyId);
		}
		
		logger.debug("added survey id == " + surveyId);
		
		model.addAttribute("surveyId", surveyId);

		return "pollCreateform";
	}

}
